<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/1
 * Time: 1:26
 */

namespace app\index\controller;

use app\index\Base;
use think\Db;
use think\Session;
use think\Url;

class Order extends Base
{

    private $param;
    private $user;

    public function __construct()
    {
        parent::__construct();
        //提交的参数
        $this->param = $this->request->param();
        $this->user = Session::get('user');
    }

    /**
     * 创建订单
     */
    public function createOrder(){
        $params = $this->param;

        $cartids = isset($params['cart_ids'])?trim($params['cart_ids']):'';
        $address_id = isset($params['address_id'])?intval($params['address_id']):0;
        $pay_type = isset($params['pay_type'])?intval($params['pay_type']):0;
        $quan_id = isset($params['quan_id'])?trim($params['quan_id']):0;
        $buy_msg = isset($params['buy_msg'])?trim($params['buy_msg']):'';

        if($this->user['m_uid']<=0){
            echo json_encode(array('code'=>4,'msg'=>'您的用户信息已过期'));die();
        }

        if($cartids==''||$address_id==0||$pay_type==0){
            echo json_encode(array('code'=>1,'msg'=>'参数错误'));die();
        }

        $data['cart_idstr'] = $cartids;
        $data['address_id'] = $address_id;
        $data['pay_type'] = $pay_type;
        $data['quan_id'] = $quan_id;
        $data['buyer_msg'] = $buy_msg;
        $data['uid'] = $this->user['m_uid'];
        $res = $this->_orderDetail($data);
        $data['goods_idstr'] = $res['goods_idstr'];
        $data['total_money'] = $res['total_money'];
        $data['youhui_money'] = $res['youhui_money'];
        $data['project'] = $res['project'];
        $data['order_sn'] = random('wx_',8);
        $data['youhui_type'] = $quan_id>0 ? 2 : 0;// 优惠方式 0没有优惠  1满减  2使用优惠券
        $data['postfee'] = $this->_postfee($res['real_money']);// 邮费
        $data['real_money'] = $res['real_money']+$data['postfee'];
        $data['pay_status'] = 0;// 1到付  2待支付0
        $data['status'] = 0;//订单状态  0 待配送   1已配送  2完成待评价
        $data['create_time'] = time();

//        生成订单
        $order_id = Db::table('kyf_order')->insert($data,false,true);
        if($order_id > 0){
            $maketmporder = $this->_makeTmpOrder($order_id);
            if($maketmporder){
                $cartids = trim($cartids,',');
                $maps['uid'] = $this->user['m_uid'];
                $maps['cart_id'] = array('in',$cartids);
                $cartst = Db::table('kyf_shopping_cart')->where($maps)->update(array('status'=>0));// 清除购物车
                //todo 即将发起支付
                echo json_encode(array('code'=>0,'msg'=>'下单成功'));die();
//                print_r($maketmporder);die();
            } else {
                echo json_encode(array('code'=>2,'msg'=>'生成临时付款订单失败'));die();
            }
        } else {
            echo json_encode(array('code'=>3,'msg'=>'生成订单失败'));die();
        }
    }


    /**
     * 生成临时订单
     */
    private function _makeTmpOrder($order_id){
        $info = Db::table('kyf_order')->where('order_id='.$order_id)->find();
        if(!empty($info)) {
            $data['tmporder_sn'] = random('wxp_', 8);
            $data['order_idstr'] = $order_id;
            $data['uid'] = $info['uid'];
            $data['pay_type'] = $info['pay_type'];
            $data['pay_status'] = 0;
            $data['money'] = $info['real_money'];
            $data['create_time'] = time();
            $data['project'] = '开元生鲜超市选购商品付款';
            $tmporder_id = Db::table('kyf_tmp_order')->insert($data,false,true);
            if($tmporder_id>0){
                return $data;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * 订单信息整合
     */
    private function _orderDetail($data){
        $res = array();
        if(isset($data['cart_idstr']) && $data['cart_idstr']!=''){
            $cart_ids = trim($data['cart_idstr'],',');
            $maps['cart_id'] = array('in',$cart_ids);
        }
        $maps['status'] = array('eq',1);
        $maps['uid'] = array('eq',$this->user['m_uid']);
        $list = Db::table('kyf_shopping_cart')->where($maps)->select();

        $goodstotal = 0;
        $project = '开元生鲜购买：';
        $goods_idstr = '';
        foreach ($list as &$val){
            $goods = Db::table('kyf_goods')->where('goods_id=' . $val['goods_id'])->find();
            $project .= $goods['short_name'].'x'.$val['buy_num'].' ';
            $goods_idstr .= $val['goods_id'].',';
            $picarr = explode(',',$goods['goods_pics']);
            $val['goods_pic'] = $picarr[0];
            $count = $goods['price'] * $val['buy_num'];
            $goodstotal+= $count;
            $val['buy_price'] = fmoney($goods['price'],false);
        }

        $res['project'] = $project;
        $res['goods_idstr'] = $goods_idstr;
        $res['total_money'] = $goodstotal;
        $quan = $this->_chekQuan($data['quan_id'],$goodstotal);// 检测优惠券使用优惠额度
        $res['youhui_money'] = $quan['youhui_money'];
        $res['real_money'] = $goodstotal-$quan['youhui_money'];
        return $res;
    }


    /**
     * 使用优惠券 优惠额度查询
     * @param $quan_id
     * @param $total
     * @return array
     */
    private function _chekQuan($uqid,$total){
        $res['youhui_money'] = 0;
        if($uqid==0) return $res;
        $userquan = Db::table('kyf_user_quan')->where('uqid='.$uqid)->find();
        $quan = Db::table('kyf_quan')->where('quan_id='.$userquan['quan_id'])->find();
        $res = array();
        if($quan['quan_type']==1) {
            if ($total > $quan['man_money']) {//满减券
                $res['youhui_money'] = $quan['youhui_money'];
            } else {
                $res['youhui_money'] = 0;
            }
        } elseif($quan['quan_type']==2){// 折扣券
            $diff = 100-$quan['discount'];
            $rate = fmoney($diff,false);//百分数变小数
            $res['youhui_money'] = $total*$rate;
        }
        return $res;
    }


    /**
     * 判断是否包邮 优惠之后 满99包邮
     * @param $real_money
     */
    private function _postfee($real_money){
        $fee = 0;
        if($real_money < 9900){
            $fee = 600;
        }
        return $fee;
    }


}